/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Aptech.JavaXML.DOMValidator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nu.xom.Attribute;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Node;
import nu.xom.Nodes;
import nu.xom.Serializer;

/**
 *
 * @author thanhtq
 */
public class CreateSurvey {

    private Document doc = null;
    public Document create(Survey survey) {
        try {
            Builder builder = new Builder();
            doc = builder.build(new File("Survey.xml"));
            Node nodes = doc.query("//Survey/categorys/category").get(0);
            Element content = new Element("content");
            content.appendChild(survey.getContentSurvey());
            Element comment = new Element("comment");
            comment.appendChild(survey.getCommenSurvey());
            Element category = new Element("category");
            Attribute id = new Attribute("id", survey.getIdSurvey());
            category.addAttribute(id);
            category.appendChild(content);
            category.appendChild(comment);
            nodes.getParent().fastInsertChild(category, nodes.getParent().getChildCount());
            return doc;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    public void removeSurvey(String id)
    {
        CreateQuestionAndAnswer create = new CreateQuestionAndAnswer();
        try {
            Builder builder = new Builder();
            doc = builder.build(new File("Survey.xml"));
            Node node = doc.query("//Survey/categorys/category").get(0);
            create.removeQuestionByCaid(id);
            Node nodeChild = doc.query("//Survey/categorys/category[@id='"+id+"']").get(0);
            //node.getParent().removeChild(nodeChild);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public boolean save() {
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(new File("Survey.xml"));
            Serializer ser = new Serializer(fos);
            ser.write(doc);
            ser.flush();            
            return true;
        }catch(Exception ex){
        return false;
        }finally{
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(CreateSurvey.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
